package com.frame.pageform;

import java.io.File;
import org.w3c.dom.*;

import com.frame.common.SystemConfig;
import com.frame.common.Xml;
import com.frame.util.BeanUtils;

public class ConfigFrame {

	private String rootPath;
	private String config;
	private String contextPath;

	public ConfigFrame(String rootPath,String config,String contextPath){
		this.rootPath=rootPath;
		this.config=config;
		this.contextPath=contextPath;
	}
	public void init(){
		try {
			Document document = Xml.createDocument(new File(rootPath+"WEB-INF/"+config));
			Element element = document.getDocumentElement();
			NodeList beannodes=Xml.getChildNodesByName(element, "bean");
			for(int b=0;b<beannodes.getLength();b++){
				try{
					Node beannode = beannodes.item(b);
					if(beannode instanceof Element){
						Element beanel=(Element)beannode;
						String classType=beanel.getAttribute("class");
						Class bean=Class.forName(classType);
						Object obj=ConfigFactory.getBean(bean);
						NodeList nodeList=beanel.getChildNodes();
						for(int i=0;i<nodeList.getLength();i++){
							Node node = nodeList.item(i);
							if(node instanceof Element)
							{
								Element el=(Element)node;
								String property=el.getAttribute("property");
								String value=el.getAttribute("value");
								BeanUtils.setValue(obj, property, value);
							}
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			SystemConfig sysConfig= (SystemConfig)ConfigFactory.getBean(SystemConfig.class);
			sysConfig.setRootPath(rootPath);
			sysConfig.setContextPath(contextPath);

			NodeList initbean=Xml.getChildNodesByName(element, "init");
			for(int b=0;b<initbean.getLength();b++){
				try{
					Node beannode = initbean.item(b);
					if(beannode instanceof Element){
						Element beanel=(Element)beannode;
						String classType=beanel.getAttribute("class");
						Class bean=Class.forName(classType);
						FrameInit obj=(FrameInit)bean.newInstance();
						obj.init();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}

			NodeList urlnodes=Xml.getChildNodesByName(element, "url-pattern");
			UrlWriteConfig urlwrite=(UrlWriteConfig)ConfigFactory.getBean(UrlWriteConfig.class);
			for(int b=0;b<urlnodes.getLength();b++){
				try{
					Node beannode = urlnodes.item(b);
					if(beannode instanceof Element){
						Element beanel=(Element)beannode;
						urlwrite.addUrlPattern(Xml.getElementValue(beanel),beanel.getAttribute("class"));
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("加载系统配置失败!");
			e.printStackTrace();
		}

	}
}
